import logging
from dataclasses import dataclass
from urllib.parse import urlparse

logger = logging.getLogger(__name__)

SECRETS = {}


@dataclass
class DBConfig:
    connection_url: str
    pool_size: int = 10
    max_overflow: int = 5
    db_schema: str = 'app_schema'
    host: str = 'localhost'
    port: str = '5432'
    user: str = 'mf'
    password: str = 'password'
    db: str = 'mf'

    def __post_init__(self) -> None:
        local_conn_url = f'postgresql+psycopg2://{self.user}:{self.password}@{self.host}:{self.port}/{self.db}'
        if not self.connection_url:
            self.connection_url = local_conn_url
            logger.info(
                'Database connection url set to default: %s', local_conn_url
            )


def load_db_config_from_env(environment: str) -> DBConfig:
    connection_url = SECRETS.get(environment, EnvironmentChoice.LOCAL).get('DB_CONN', '')  # type: ignore

    masked_pwd = '*****'
    url = urlparse(connection_url)
    masked_url = f'{url.scheme}://{url.username}:{masked_pwd}@{url.hostname}:{url.port}{url.path}?{url.query}'

    logger.info('Database connection url: %s', masked_url)

    return DBConfig(connection_url=connection_url)
